package com.suse.jd_system_server.utils;

import com.suse.jd_system_server.entity.Authority;
import com.suse.jd_system_server.entity.User;
import com.suse.jd_system_server.service.LoginService;
import com.suse.jd_system_server.service.impl.LoginServiceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private LoginServiceImpl loginService;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = loginService.selectUserByName(username);
        if (null==user){
            throw new UsernameNotFoundException("用户不存在");
        }
        if (user.getStatus()==0){
            throw new RuntimeException("用户未激活");
        }
        List<String> sysMenus = loginService.selectAuthority(user.getUserId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //方式一
        for(String menu : sysMenus){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(menu);
            authorities.add(simpleGrantedAuthority);
        }
        //方式二
        //List<SimpleGrantedAuthority> authorityList = sysMenus.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        SecurityUser securityUser = new SecurityUser(user);
        securityUser.setAuthorities(authorities);
        return securityUser;
    }
}
